using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;

namespace dataXJobGenerator
{
    public class TablesConfiguration
    {
        public string Table { get; private set; }
        public int Record { get; set; }
        public int Sort { get; set; }
        public string TableMapTo { get; private set; }
        public List<string> TablePreSql { get; set; } = new List<string>();

        public List<string> TablePostSql { get; set; } = new List<string>();

        public List<string> MapToPreSql { get; set; } = new List<string>();

        public List<string> MapToPostSql { get; set; } = new List<string>();
        public string Job { get; set; }
        public List<ColumnMapItem> Columns { get; set; } = new List<ColumnMapItem>();


        public static IEnumerable<TablesConfiguration> GetTableConfigurations(IConfiguration configuration)
        {
            var tablesConfigurationsConfigurations = new List<TablesConfiguration>();

            var tableConfigs = configuration.GetSection("Tables").GetChildren();
            foreach (var section in tableConfigs)
            {
                var config = new TablesConfiguration();
                config.Table = section.GetValue("table");
                config.TableMapTo = section.GetValue("mapTo");

                config.MapToPreSql.AddRange(section.GetValues("mapToPreSql"));
                config.MapToPostSql.AddRange(section.GetValues("mapToPostSql"));
                
                config.TablePreSql.AddRange(section.GetValues("tablePreSql"));
                config.TablePostSql.AddRange(section.GetValues("tablePostSql"));

                var mappings = section.GetSection("columns").GetChildren();
                foreach (var mapping in mappings)
                {
                    var mapItem = new ColumnMapItem();
                    mapItem.Source = mapping.GetValue("src");
                    mapItem.Destination = mapping.GetValue("dest");
                    config.Columns.Add(mapItem);
                }

                tablesConfigurationsConfigurations.Add(config);
            }

            return tablesConfigurationsConfigurations;
        }

        public class ColumnMapItem
        {
            public string Source { get; set; }
            public string Destination { get; set; }
        }
    }
}